package plgutils

import (
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"gitee.com/ymofen/gobase/golog"
	"os"
	"strings"
	"time"
)

var (
	plg_templ_http_ctrl string = `
  {
    "id": "net.http.plgctrl",
    "type": "net.http.plgctrl",
    "conf": {
      "addr": "$cmd-addr$",
      "caption":"插件框架控制"
    }
  }
`
	plg_templ_fatalog string = `
  {
    "id":"fatal-log",
    "type":"core.fatal.log",
    "conf":{
      "filename":"$filename$"
    }
  }
`

	plg_templ_app_log string = `
  {
    "id":"applog",
    "type":"core.sflogger.filelogger",
    "conf":{
      "filename":"$filename$",
      "format":"[%D %T] [%L] %M (%S)\r\n",
      "loglvl":"$LVL$",
      "loglvlop":">=",
      "maxfilesize":"50M"
    }
  }
`
)

func LoadStartupConfFilePlug(conffile string) {
	strconf := `
[
  {
     "id":"startup4configfile",
     "type": "utils.plug.maker.mix",
     "changedlst":0,
     "conf": {
        "filename-json":"$$conffile$$",
        "reload-interval-secs":10,
        "checkremove-flag":1,
        "load-delay-secs": 0
     }
  }
]`
	strconf = strings.ReplaceAll(strconf, "$$conffile$$", utils.EscapeJsonStrSimple(conffile))
	_, _, err := plgbase.ReloadPlugsJSONStr(strconf)
	if err != nil {
		golog.Infof("加载插件异常:%s", err.Error())
	}
}

func innerStartUpHttpCtrl(cmdaddr string) error {
	strv := strings.ReplaceAll(plg_templ_http_ctrl, "$cmd-addr$", cmdaddr)
	_, _, err := plgbase.PlgCheckReloadFromJSONStr(strv)
	return err
}

func StartHttpCtrl(cmdaddr string) error {
	strv := strings.ReplaceAll(plg_templ_http_ctrl, "$cmd-addr$", cmdaddr)
	_, _, err := plgbase.PlgCheckReloadFromJSONStr(strv)
	return err
}

func StartupFatalog(logfile string) {
	if len(logfile) == 0 {
		logfile = utils.CombineFilePath("log", "fatal-#yyyy##mm##dd#.log")
	}
	str := strings.ReplaceAll(plg_templ_fatalog, "$filename$", logfile)

	_, _, err := plgbase.PlgCheckReloadFromJSONStr(str)
	if err != nil {
		golog.Warnf("%s", err.Error())
		time.Sleep(time.Second)
	}

}

func StartupAppLog(logfile string, loglvl string) {
	if len(logfile) == 0 {
		logfile = utils.CombineFilePath("log", "app.log")
	}
	if len(loglvl) == 0 {
		loglvl = "DEBUG"
	}

	str := strings.ReplaceAll(plg_templ_app_log, "$filename$", logfile)
	str = strings.ReplaceAll(str, "$LVL$", loglvl)

	_, _, err := plgbase.PlgCheckReloadFromJSONStr(str)
	if err != nil {
		golog.Warnf("%s", err.Error())
		time.Sleep(time.Second)
	}
}

func StartupConfigByArgs() {
	var debug_mode int
	var workers_cnt int
	utils.TryFlagParse(func(cmd *utils.FlagSet) {
		cmd.IntVar(&debug_mode, "debug-mode", -1, "-debug-mode=1")
		cmd.IntVar(&workers_cnt, "work-n", -1, "-work-n=128")
	})

	if debug_mode != -1 {
		utils.DEBUG_MODE = debug_mode
	}

	if workers_cnt > 0 {
		utils.DefaultWorkers().ConfigMaxWork(int32(workers_cnt))
	}

}

func StartupDefaultPlgByArgs() {
	var cmd_addr string
	var conf_file string
	utils.TryFlagParse(func(cmd *utils.FlagSet) {
		cmd.StringVar(&cmd_addr, "cmd-addr", "", "")
		cmd.StringVar(&conf_file, "config-file", "", "")
	})

	if len(os.Args) == 2 && len(conf_file) == 0 && os.Args[1][0] != '-' {
		conf_file = os.Args[1]
	}

	if len(cmd_addr) > 0 {
		utils.RegisterFactoryVarFunc("startup.cmd-addr", func(sender interface{}, args ...interface{}) interface{} {
			return cmd_addr
		})
		innerStartUpHttpCtrl(cmd_addr)

	}

	if len(conf_file) > 0 {
		utils.RegisterFactoryVarFunc("startup.config-file", func(sender interface{}, args ...interface{}) interface{} {
			return conf_file
		})

		LoadStartupConfFilePlug(conf_file)
		//plgbase.CheckReloadPlgFormFile(conf_file)
		//plgbase.AddSysReloadNotify("StartupDefaultPlgByArgs", func() {
		//	plgbase.CheckReloadPlgFormFile(conf_file)
		//})
	}
}
